package com.zone.gateway.assist.listener;

import com.zone.gateway.assist.config.ApiGatewayProperties;
import com.zone.gateway.assist.domain.service.GatewayCenterService;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.util.List;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/5/7
 */
public class RedisMessageRpcRegisterListener implements MessageListener {
    private final GatewayListener gatewayListener;
    private final GatewayCenterService registerService;
    private final ApiGatewayProperties properties;

    public RedisMessageRpcRegisterListener(GatewayListener gatewayListener, GatewayCenterService registerService, ApiGatewayProperties properties) {
        this.gatewayListener = gatewayListener;
        this.registerService = registerService;
        this.properties = properties;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        // topic
        String channel = new String(bytes);
        // systemId
        String systemId = new String(message.getBody());
        // 查询应用对应的网关
        List<String> gatewayIds = registerService.queryGatewayIds(properties.getRegisterUrl(), systemId);
        // 重新注册网关
        for (String gatewayId : gatewayIds) {
            gatewayListener.addMapper(gatewayId);
        }
    }
}
